//
//  NetWorkingSupport.swift
//  DriverSchoolAPP
//
//  Created by Logel on 2017/4/20.
//  Copyright © 2017年 Logel. All rights reserved.
//

import Foundation           
import Alamofire
import UIKit

//MARK:-网络请求回调
protocol LgCallBack {
    func callBack(method:String,data:AnyObject)
}

//MARK:-异步Post请求

func asyn_req_post(method:String,cb:LgCallBack,p:[String:AnyObject]){
    let url = API_URL + method
    print(url)
    Alamofire.request(url, method: .post, parameters: p, encoding: JSONEncoding.default, headers: nil).responseJSON { (resp) in
        print(p)
//        if let error = resp.result.error{
//            print(error)
//        }else if let value = resp.result.value{
//            cb.callBack(method: method, data: value as AnyObject)
//        }
        switch resp.result {
        case .success:
            cb.callBack(method: method, data: resp.result.value! as AnyObject)
        case .failure(let Error):
            print(Error)
        
        }
        
    }

}

func showMsg(msg:String){
    let alert = UIAlertView(title: "提示", message: msg, delegate: nil, cancelButtonTitle: "确定")
    alert.show()
}


func getImageWithUrl(url:String)->UIImage{
    var img = UIImage()
    let url:URL = (URL(string: url))!
    do {
        let d1:Data = try Data(contentsOf: url)
        img = UIImage(data: d1)!
       
    } catch {
        
    }
     return img
}
/*  使用NSUserDefaults对普通数据对象储存   */

/**
 储存
 
 - parameter key:   key
 - parameter value: value
 */
 func setNormalDefault(key:String, value:AnyObject?){
    if value == nil {
        UserDefaults.standard.removeObject(forKey: key)
    }
    else{
        UserDefaults.standard.set(value, forKey: key)
        // 同步
        UserDefaults.standard.synchronize()
    }
}

/**
 通过对应的key移除储存
 
 - parameter key: 对应key
 */
 func removeNormalUserDefault(key:String?){
    if key != nil {
        UserDefaults.standard.removeObject(forKey: key!)
        UserDefaults.standard.synchronize()
    }
}

/**
 通过key找到储存的value
 
 - parameter key: key
 
 - returns: AnyObject
 */
 func getNormalDefult(key:String)->String?{
    return UserDefaults.standard.value(forKey: key) as! String?
}

/**
 字典转换为JSONString
 
 - parameter dictionary: 字典参数
 
 - returns: JSONString
 */
func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
    if (!JSONSerialization.isValidJSONObject(dictionary)) {
        print("无法解析出JSONString")
        return ""
    }
    let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData!
    let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
    return JSONString! as String
    
}

func toolsChangeToJson(info: Any) -> String{
    //首先判断能不能转换
    guard JSONSerialization.isValidJSONObject(info) else {
        print("json转换失败")
        return ""
    }
    //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
    let jsonData = try? JSONSerialization.data(withJSONObject: info, options: [])
    
    if let jsonData = jsonData {
        let str = String(data: jsonData, encoding: String.Encoding.utf8)
        return str ?? ""
    }else {
        return ""
    }
}

public protocol CGYJSON {
    func toJSONModel() -> AnyObject?
    func toJSONString() -> String?
}

extension CGYJSON {
    public func toJSONModel() -> AnyObject? {
        let mirror = Mirror(reflecting: self)
        guard mirror.children.count > 0 else {
            return self as? AnyObject
        }
        var result: [String: AnyObject] = [:]
        var superClss = mirror.superclassMirror
        while superClss != nil {
            for case let (label?, value) in superClss!.children {
                if let jsonValue = value as? CGYJSON {
                    result[label] = jsonValue.toJSONModel()
                }
            }
            superClss = superClss?.superclassMirror
        }
        for case let (label?, value) in mirror.children {
            if let jsonValue = value as? CGYJSON {
                result[label] = jsonValue.toJSONModel()
            }
        }
        return result as AnyObject?
    }
    
    public func toJSONString() -> String? {
        guard let jsonModel = self.toJSONModel() else {
            return nil
        }
        let data = try? JSONSerialization.data(withJSONObject: jsonModel, options: [])
        let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        return str as? String
    }
}

extension Optional: CGYJSON {
    public func toJSONModel() -> AnyObject? {
        if let _self = self {
            if let value = _self as? CGYJSON {
                return value.toJSONModel()
            }
        }
        return NSNull()
    }
}

extension Array: CGYJSON {
    public func toJSONModel() -> AnyObject? {
        var results: [AnyObject] = []
        for item in self {
            if let ele = item as? CGYJSON {
                if let eleModel = ele.toJSONModel() {
                    results.append(eleModel)
                }
            }
        }
        return results as AnyObject?
    }
}

extension Dictionary: CGYJSON {
    public func toJSONModel() -> AnyObject? {
        var results: [String: AnyObject] = [:]
        for (key, value) in self {
            if let key = key as? String {
                if let value = value as? CGYJSON {
                    if let valueModel = value.toJSONModel() {
                        results[key] = valueModel
                        continue
                    }
                } else if let value = value as? AnyObject {
                    results[key] = value
                    continue
                }
                results[key] = NSNull()
            }
        }
        return results as AnyObject?
    }
}

extension Date: CGYJSON {
    public func toJSONModel() -> AnyObject? {
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        return dateFormat.string(from: self) as AnyObject?
    }
}

extension String: CGYJSON {}
extension Int: CGYJSON {}
extension Int8: CGYJSON {}
extension Int16: CGYJSON {}
extension Int32: CGYJSON {}
extension Int64: CGYJSON {}
extension UInt: CGYJSON {}
extension UInt8: CGYJSON {}
extension UInt16: CGYJSON {}
extension UInt32: CGYJSON {}
extension UInt64: CGYJSON {}
extension Bool: CGYJSON {}
extension Float: CGYJSON {}
extension Double: CGYJSON {}


func getWeekDay(dateTime:String)->Int{
    let dateFmt = DateFormatter()
    dateFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let date = dateFmt.date(from: dateTime)
    date!.description
    let interval = Int(date!.timeIntervalSince1970)
    let days = Int(interval/86400) // 24*60*60
    let weekday = ((days + 4)%7+7)%7
    return weekday == 0 ? 7 : weekday
}


extension UIButton {
    
    @objc func set(image anImage: UIImage?, title: String,
                   titlePosition: UIViewContentMode, additionalSpacing: CGFloat, state: UIControlState){
        self.imageView?.contentMode = .center
        self.setImage(anImage, for: state)
        
        positionLabelRespectToImage(title: title, position: titlePosition, spacing: additionalSpacing)
        
        self.titleLabel?.contentMode = .center
        self.setTitle(title, for: state)
    }
    
    private func positionLabelRespectToImage(title: String, position: UIViewContentMode,
                                             spacing: CGFloat) {
        let imageSize = self.imageRect(forContentRect: self.frame)
        let titleFont = self.titleLabel?.font!
        let titleSize = title.size(attributes: [NSFontAttributeName: titleFont!])
        
        var titleInsets: UIEdgeInsets
        var imageInsets: UIEdgeInsets
        
        switch (position){
        case .top:
            titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
        case .bottom:
            titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),
                                       left: -(imageSize.width), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
        case .left:
            titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,
                                       right: -(titleSize.width * 2 + spacing))
        case .right:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        default:
            titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }
        
        self.titleEdgeInsets = titleInsets
        self.imageEdgeInsets = imageInsets
    }
}

func getHHMMSSFormSS(seconds:Int) -> String {
    let str_hour = NSString(format: "%02ld", seconds/3600)
    let str_minute = NSString(format: "%02ld", (seconds%3600)/60)
    let str_second = NSString(format: "%02ld", seconds%60)
    let format_time = NSString(format: "%@:%@:%@",str_hour,str_minute,str_second)
    return format_time as String
}

//第一步测试
//        Alamofire.request("https:httpbin.org/get").responseJSON { response in
//            print(response.request)
//            print(response.response)
//            print(response.data)
//            print(response.result)
//
//            if let JSON = response.result.value{
//                print("JSON:\(JSON)")
//            }
//        }

//     Alamofire.request(URLStringGetBooks, method: .get, parameters: ["tag":"Swift","count":10]).responseJSON { (resp) in
//        if let error = resp.result.error{
//            print(error)
//        }else if let value = resp.result.value{
//            print(value)
//        }
//
//
//    }

//        Alamofire.request("http://172.20.10.2:9102/members/register", method: .post, parameters: ["userName":"15025161350","passWord":"123456","valideCode":"111111","sources":"iOS"],encoding: JSONEncoding.default, headers: nil).responseJSON { (resp) in
//
//
//            print(resp.result.value!)
//            let j = JSON(resp)
//            print(j)
//
//            if let error = resp.result.error{
////                print(error)
////                let s = String(data: resp.data!, encoding: .utf8)
////                print(s)
//            }else if let value = resp.result.value{
//               // print(value)
//
//            }
//
//
//        }

//        let headers: HTTPHeaders = [
//            "X-Authorization": "Bearer \(token)",
//            "Accept": "application/json"
//        ]

//        Alamofire.request(loginUrl, method: .post, parameters: ["username":"test","password":"123456"], encoding: JSONEncoding.default, headers: nil).responseJSON { (resp) in
//            if let error = resp.result.error{
//                print(error)
//            }else if let value = resp.result.value{
//                print(value)
//            }
//
//
//        }

//        Alamofire.request(TestUrl,method:.get, headers: headers).responseJSON { (resp) in
//            if let error = resp.result.error{
//                print(error)
//            }else if let value = resp.result.value{
//                print(value)
//            }
//
//
//        }


//Alamofire.request(loginUrl, method: .get,Parameters:[], encoding: JSONEncoding.default, headers: HTTPHeaders).re

// Alamofire.request(loginUrl, method: .get, parameters: [], encoding: JSONEncoding.default, headers: HTTPHeaders)
// Do any additional setup after loading the view.
